/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package TrapezoidalRule;

import java.util.Scanner;
import java.util.StringTokenizer;

/**
 *
 * @author pol
 */
public class Trapezoidal {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Function to integrate f(x) = ");
        String s = in.nextLine();
        System.out.print("a = ");
        Double a = in.nextDouble();
        System.out.print("b = ");
        Double b = in.nextDouble();
        System.out.print("Eps(please input no more 100000) = ");
        Double eps = in.nextDouble();
        System.out.println(trapezium(s, a, b, eps));
    }

    private static String[] getTokens(String s) {
        StringTokenizer st = new StringTokenizer(s, "+-/*()^x", true);
        String[] str = new String[st.countTokens()];
        int i = 0;
        while (st.hasMoreTokens()) {
            str[i++] = st.nextToken();
        }
        return str;
    }

    public static Double trapezium(String func, Double a, Double b, Double eps) {
        double sum = 0.0;
        double h = (double) (b - a) / (eps);
        for (double i = a; i < b; i += h) {
            PostfixNotation pn = new PostfixNotation();
            double f = Double.parseDouble(pn.calculate(getTokens(func), Double.toString(i)));
            sum += f;
        }
        PostfixNotation pn = new PostfixNotation();
        double fa = Double.parseDouble(pn.calculate(getTokens(func), Double.toString(a)));
        double fb = Double.parseDouble(pn.calculate(getTokens(func), Double.toString(b)));
        sum = (sum + 0.5 * (fa + fb)) * h;
        return sum;
    }
}
